package com.leetcode.LeetCode精选TOP面试题;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 覃国强
 * @date 2022-05-18 18:21
 */
public class 题库_0017_电话号码的字母组合 {

  static
  class Solution {

    private static final String[] phoneLetters = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    public List<String> letterCombinations(String digits) {
      if (digits == null || digits.length() == 0) {
        return new ArrayList<>();
      }
      List<String> answer = new ArrayList<>();
      backtrack(answer, new char[digits.length()], 0, digits);
      return answer;
    }

    private void backtrack(List<String> answer, char[] letters, int index, String digits) {
      if (index == letters.length) {
        answer.add(new String(letters));
        return;
      }
      char digit = digits.charAt(index);
      String phoneLetter = phoneLetters[digit - '2'];
      for (char ch : phoneLetter.toCharArray()) {
        letters[index] = ch;
        backtrack(answer, letters, index + 1, digits);
      }
    }

  }

  static
  class Solution2 {

    private static final Map<Character, String> phoneLetter = new HashMap<>();
    static {
      phoneLetter.put('2', "abc");
      phoneLetter.put('3', "def");
      phoneLetter.put('4', "ghi");
      phoneLetter.put('5', "jkl");
      phoneLetter.put('6', "mno");
      phoneLetter.put('7', "pqrs");
      phoneLetter.put('8', "tuv");
      phoneLetter.put('9', "wxyz");
    }

    public List<String> letterCombinations(String digits) {
      if (digits == null || digits.length() == 0) {
        return new ArrayList<>();
      }
      List<String> answer = new ArrayList<>();
      answer.add("");

      for (int i = 0; i < digits.length(); ++i) {
        String letter = phoneLetter.get(digits.charAt(i));
        List<String> temp = new ArrayList<>();
        for (char ch : letter.toCharArray()) {
          for (String str : answer) {
            temp.add(str + ch);
          }
        }
        answer = temp;
      }

      return answer;
    }
  }

}
